#include "timeout.h"
#include "user_tim.h"
#include "./tlsf/tlsf_porting.h"

/********************静态变量定义********************/
timeout_event_t *timeout_event_list = NULL; /*超时事件链表头指针*/

/********************全局函数定义********************/
 
/**
 * @brief 超时事件挂载函数
 * @param queue 用于接收超时事件的队列
 * @param timeout 超时时间
 * @param event 超时事件
 */
void mount_timeout_event(lwq_t *queue, uint32_t timeout, int timeout_event) 
{
    timeout_event_t *new_event = (timeout_event_t *)pool_malloc(sizeof(timeout_event_t));
	
    new_event->queue = queue;
    new_event->timeout = sys_tick_get() + timeout;
    new_event->event.event = timeout_event;
	new_event->event.data = NULL;
    new_event->next = NULL;

    /*将新事件插入到链表中*/
    if (timeout_event_list == NULL) 
	{
        timeout_event_list = new_event;
    } 
	else 
	{
        timeout_event_t *current = timeout_event_list;
		
        while (current->next != NULL) 
		{
            current = current->next;
        }
        current->next = new_event;
    }
}

/**
 * @brief 超时事件管理函数
 */
void manage_timeout_event(void) 
{
    uint32_t current_time = sys_tick_get();
    timeout_event_t *current = timeout_event_list;
    timeout_event_t *prev = NULL;

    while (current != NULL) 
	{
        if (current->timeout <= current_time) 
		{
            /*超时事件到达，发送事件到对应的状态机消息队列*/
            lwq_write(current->queue, &current->event);

            /*从链表中删除该事件*/
            if (prev == NULL) 
			{
                timeout_event_list = current->next;
            } 
			else 
			{
                prev->next = current->next;
            }
			
            timeout_event_t *temp = current;
            current = current->next;
            pool_free(temp);
        } 
		else 
		{
            prev = current;
            current = current->next;
        }
    }
}


